<html>
  <head>
  <title>CBE BPE Toolkit - Trending</title>
    <link rel="stylesheet" type="text/css" href="/static/bootstrap/css/bootstrap.css">
    <link rel="stylesheet" type="text/css" href="/static/anytime/css/anytimec.css"/>                                                                
    <link rel="stylesheet" type="text/css" href="/static/jquery-ui/css/smoothness/jquery-ui-1.8.16.custom.css"/>                                 
    <link rel="stylesheet" type="text/css" href="/static/pmp/css/plot.css"/>
    <!--<link rel="stylesheet" type="text/css" href="/static/pmp/css/plot.css"/>-->
    <style type="text/css">
      body {
        padding-top: 60px;
        padding-bottom: 40px;
      }
      .sidebar-nav {
        padding: 9px 0;
      }
    </style>                                                                    

    <!--script type="text/javascript" src="/static/jquery-1.5.2/jquery-1.5.2.min.js"></script>
   	<script type="text/javascript" src="/static/jquery-1.5.2/jquery.cookie.js"></script>
    <script type="text/javascript" src="/static/jquery-1.5.2/jquery.hotkeys.js"></script>-->
    <script type="text/javascript" src="/static/jquery-1.7.2/jquery-1.7.2.min.js"></script>
    <script type="text/javascript" src="/static/flot-0.7/js/jquery.flot.js"></script>
    <script type="text/javascript" src="/static/flot-0.7/js/jquery.flot.stack.min.js"></script>
    <script type="text/javascript" src="/static/flot-0.7/js/jquery.flot.navigate.min.js"></script>
    <script type="text/javascript" src="/static/flot-0.7/js/jquery.flot.selection.min.js"></script>
    <script type="text/javascript" src="/static/flot-0.7/js/date.js"></script>
    <script type="text/javascript" src="/static/jquery-ui/development-bundle/ui/jquery.ui.core.js"></script>
    <script type="text/javascript" src="/static/jquery-ui/development-bundle/ui/jquery.ui.widget.js"></script>
    <script type="text/javascript" src="/static/jquery-ui/development-bundle/ui/jquery.ui.button.js"></script>
    <script type="text/javascript" src="/static/jquery-ui/development-bundle/ui/jquery.ui.position.js"></script>
    <script type="text/javascript" src="/static/jquery-ui/development-bundle/ui/jquery.ui.dialog.js"></script>
    <script type="text/javascript" src="/static/jquery-ui/development-bundle/ui/jquery.ui.mouse.js"></script>
    <script type="text/javascript" src="/static/jquery-ui/development-bundle/ui/jquery.ui.resizable.js"></script>
    <script type="text/javascript" src="/static/jquery-ui/development-bundle/ui/jquery.ui.draggable.js"></script>
    <script type="text/javascript" src="/static/anytime/js/anytimec.js"></script>
    <script type="text/javascript" src="/static/smap/js/lib.js"></script>
    <script type="text/javascript" src="/static/pmp/js/plot.js"></script>
    <script type="text/javascript" src="/static/flot-0.7/js/colormap.js"></script>
    <script type="text/javascript" src="/static/pmp/js/tagtreeTrending.js"></script>
    <script type="text/javascript" src="/static/jsTree/jquery.jstreeRC1.js"></script>    
	<script type="text/javascript" src="/static/bootstrap/js/bootstrapTrending.js"></script>
	<script type="text/javascript" src="/static/sessvars/sessvars.js"></script>
	<script type="text/javascript" src="/static/jquery-blockUI/jquery.blockUI.js"></script>
	<script type="text/javascript" src="/static/pmp/js/pmputil.js"></script>
</head>
  <body>
  	   {% include 'header.html' %}
    <div class="span10" id="mainContent">
	    <div id="nav" title="Select streams ('alt' key to select multiple)">
	    	<div id="tree_div"></div>
	    </div>	
      
      <div class="chart_wrapper" style="width:800px; height: 400px;">
        <div id="yaxisLabel" name="label"></div>
        <div id="chart_div" style="width:750; height: 100%; float: right;"></div>
        <div id="yaxis2Label"></div>
      </div>
      <div id="xaxisLabel"></div>
      <div id="chart_controls">
			<div class="btn-toolbar">
			<form class="form-inline" style="margin-bottom: 9px">
			<input type="text" id="startDate" class="input-large"><span style="font-size: 11px">&nbsp;Start date&nbsp;
        	<input type="text" id="endDate" class="input-large">&nbsp;End date&nbsp;</span>&nbsp;&nbsp;
			
		    <button onclick="advanceTimeSmap(false); return false;" class="btn btn-small"><i class="icon-step-backward"></i></button>
	        <div class="btn-group">
	        <input type="button" id="plotbutton" value="Plot" class="btn btn-small">
	        <input type="button" id="reloadbutton" value="Reload" class="btn btn-small">
	        </div>
	        <button onclick="advanceTimeSmap(true); return false;" class="btn btn-small"><i class="icon-step-forward"></i></button>
	        	        
	        </form>
	        </div>
		<div class="btn-toolbar">
			<div class="btn-group">
				<input type="button" onclick="javascript: setEndNow(true); $('#btnGrp1').button('reset');" value="Recent" class="btn btn-small">
		        <input type="button" onclick="javascript: setEndNow(false); $('#btnGrp1').button('reset');" value="Now" class="btn btn-small">
		        <input type="button" onclick="javascript: plotInitSmap(true); $('#btnGrp1').button('reset');" value="Reset" class="btn btn-small">
	        </div>
	        <div class="btn-group" data-toggle="buttons-radio" id='btnGrp1'>
		        <input type="button" onclick="javascript: changeDatesSmap('hour');" value="Hour" id="hrbtn" class="btn btn-small">
		        <input type="button" onclick="javascript: changeDatesSmap('day');" value="Day" id="dybtn" class="btn btn-small">
		        <input type="button" onclick="javascript: changeDatesSmap('week');" value="Week" id="wkbtn" class="btn btn-small">
		        <input type="button" onclick="javascript: changeDatesSmap('month');" value="Month" id="mnthbtn" class="btn btn-small">
	        </div>
        <!--<input type="checkbox" id="autoupdate" onchange="javascript: null;">&nbsp;Autoupdate</input>-->
        <input type="checkbox" id="no_resample">&nbsp;Disable auto-resampling</input>
        <input type="checkbox" id="maintain_zoom">&nbsp;Maintain y-axis zoom</input>
       </div>
       <div class="btn-toolbar">
		<form class="form-inline">
		<input type="button" id="selectbutton" value="Select streams" class="btn btn-small">
		<input type="button" id="controlsbutton" value="Chart options" class="btn btn-small">
		<input type="button" id="clearbutton" value="Clear" class="btn btn-small">&nbsp;|
		<div class="btn-group">
        <input type="button" id="csvbutton" disabled="true" value="Export csv" class="btn btn-small">
        <input type="button" id="csvAllButton" value="Export all points csv" class="btn btn-small">
        </div>
        <div class="input-append"><input type="text" id="resampleTime" class="input-small" value="15" style="height: 28px"><span class="add-on" style="font-size: 11px">minutes</span></div>
        &nbsp;|&nbsp;<a id="permalink" href="">permalink</a>&nbsp;|&nbsp;<a target="_blank" href="/static/doc/_build/html/trending.html"><i class="icon-info-sign"></i></a>
        </div>    
      </div>
      
      <div id="c_controls" title="Chart options">
      	<div class="controls">
      	<label style="font-size: 11px"><b>Mouse mode</b></label>
      	<label class="radio" style="font-size: 10px; margin-top: 5px"><input name="select_mode" type="radio" value="zoom" onchange="javascript: updatePlot(true)" checked>Zoom</label>
        <label class="radio" style="font-size: 10px"><input name="select_mode" type="radio" value="hover" onchange="javascript: updatePlot(true)">Hover</label>
      	</div>
      	
      	<label style="font-size: 11px"><b>Display styles</b>&nbsp;&nbsp;<button onclick="javascript: updatePlot(true)"><i class="icon-refresh"></i></button></label>
  		<label class="checkbox" style="font-size: 10px"><input type="checkbox" id="hweekends" onchange="javascript: showHoo(); updatePlot(true)">Operational hours </label>
  		<div id="hoo" style="margin-left: 15px">
		<label class="checkbox" style="font-size: 10px"><input type="checkbox" id="wkdays">Weekdays only</label>
   		<input type="text" id="startHour" class="input-mini" value="06"><font style="font: 10px sans-serif">&nbsp;Start hour</font>
   		<input type="text" id="endHour" class="input-mini" value="18"><font style="font: 10px sans-serif">&nbsp;End hour</font>
  		</div>
  		<label class="checkbox" style="font-size: 10px"><input type="checkbox" id="dinstances" onchange="javascript: updatePlot(true)">Device instances</label>
  		<label class="checkbox" style="font-size: 10px"><input type="checkbox" id="stack" onchange="javascript: updatePlot(true)">Stack</label>
	    <script>
			$("#startHour").AnyTime_noPicker().AnyTime_picker( { format: "%H", labelTitle: "Start hour",labelHour: "Hour"} ).focus();
			$("#endHour").AnyTime_noPicker().AnyTime_picker( { format: "%H", labelTitle: "End hour",labelHour: "Hour"} ).focus();
		</script>
  		
      </div>
      <div style="text-align: right; margin-top: 12pt;">
        <div id="identifier" style="float:left"></div>
      </div>
      <div class="legend">
        <div id="description" style="float: left; clear: left"></div>
      </div>
      <script type="text/javascript">
	    if (typeof sessvars.sessionObj == 'undefined'){sessvars.sessionObj = {'projectId': $('select#id_name').find("option:selected").val()};}
		if (typeof sessvars.sessionObj != 'undefined'){
			if (sessvars.sessionObj['projectId'] == ""){sessvars.sessionObj['projectId'] = $('select#id_name').find("option:selected").val();}
			else {
				for (var i=0;i<document.getElementById('id_name').options.length;i++) {
					if (document.getElementById('id_name').options[i].value == sessvars.sessionObj['projectId'])
						{document.getElementById('id_name').options[i].selected = true;}
				}
			}
		}
		$(document).ready(function(){
      		$("li#" + window.location.pathname.substring(5, window.location.pathname.length - 1)).addClass("active")
		    $('select#id_name').change(function() { 
	    		var projectId = $(this).val();
	    		sessvars.sessionObj['projectId'] = projectId
	    		projectName = $(this).find("option:selected").text();
				updateTree(projectName);
				plotInitSmap(true);
	    	})
	    	$('#btnGrp1').button('reset');
		    $('#startDate').click(function() {
	    		$('#btnGrp1').button('reset');
	    	});
	    	$('#endDate').click(function() {
	    		$('#btnGrp1').button('reset');
	    	});
	    	$('#reloadbutton').click(function(){
	    		reloadData();
	    	});
	    })
	    $('.nav-tabs').button()
        showHoo();
        var projectName = $("#id_name option:selected").text();
        var url = "{{conf.SERVER}}{{conf.PATH}}";
        var backend = "/backend";
        var private_flags = "";
        var path = "{{conf.PATH}}";
        var streamids = {}; 
        var defaultLabels = ["Metadata__SourceName", "Path"];
        // indicate whether existing streams should be removed when the next
        //  stream is selected.  this can be used to defer clearing the plot
        //  when the tree is changed, for instance.
        var clear_streams = false;
		$.ajax({
				type: "GET",
				url: "/pmp/utils/",
				data: {'projectId': sessvars.sessionObj['projectId'], 'utilType': 'tz'},
				success: function(data){
				tz = data	 
				},
				async: false
			});
        plotInitSmap();
        timezoneJS.timezone.zoneFileBasePath = "/static/tz";
        timezoneJS.timezone.init();
        $("#clearbutton").click(clearPlot);
        $("#csvbutton").click(exportCsvAll);
        $("#csvAllButton").click(exportAllPointsCsv);
        $("#selectbutton").click(function() {
          $("#nav").dialog("open") ;
        });
        $("#controlsbutton").click(function() {
          $("#c_controls").dialog("open") ;
        });

        // set up the stream dialog
        $("#nav").dialog({height: 600, width: 300, 
                          position: [1375,50], show: "slide",
                          hide: "slide",
                          resizable: true, dialogClass: "flora",
                          autoOpen: !(page_args.streamids) || page_args.path});
        //$(window).resize(function() {
        //  $("#nav").dialog("option", {height: $(window).height()-200});
        //});
        //$('.flora.ui-dialog').css({position:"fixed"});
		//setup the control dialog
		$("#c_controls").dialog({height: 300, width: 200, 
                          position: [1150,50], show: "slide",
                          hide: "slide",
                          resizable: true, dialogClass: "flora", autoOpen: false,
                         });

        function togglePrivate() {
          if (!private_flags) {
            backend = "/backend_auth";
            private_flags = "private=None";
            // private_flags = '';
            $("#ptoggle").text("public streams");
          } else {
            backend = "/backend";
            private_flags = "";
            $("#ptoggle").text("private streams");
          }
          updateTree(projectName);
        }

        function clearPlot() {
          document.getElementById("permalink").href = "";
          document.getElementById("description").innerHTML = "";
          plotterClearPlot();
          streamids = {};
        }

        function selectCb(path, tags, labels) {
          if (tags.length > 5) {
            if (!confirm("Found " + tags.length + " streams; show 5?")) return;
          }

          if (labels == undefined) {
            labels = defaultLabels;;
          }

          if (clear_streams) {
            clear_streams = false;
            clearPlot();
          }

          if (!(path in streamids)) {
            streamids[path] = [];
          }
          //this is how it is able to plot per folder
          for (var i = 0; i < tags.length; i++) {
            streamids[path].push(tags[i]["uuid"]);
          }

          addStreams(tags, labels, 5);
        }

        function deselectCb(path) {
          if (!(path in streamids)) return;
          for (var i = 0; i < streamids[path].length; i++) {
            delStream(streamids[path][i]);
          }
          streamids[path] = [];
        }
		
        var treeidx = 0
        function updateTree(projectName) {
        	if (projectName == 'sdh'){
        		var trees = [
		        [{tag: "Metadata/SourceName",
		        restrict: "Metadata/SourceName = 'Sutardja Dai Hall BACnet' or Metadata/Extra/Project = '" + projectName + "'"},
		        {"prefixTag": "Path"}],
				];
        	}
        	else if (projectName == 'bancroft'){
        		var trees = [
		        [{tag: "Metadata/SourceName",
		        restrict: "Metadata/SourceName = 'Bancroft Library' or Metadata/Extra/Project = '" + projectName + "'"},
		        {"prefixTag": "Path"}],
				];
        	}
        	else{
	        	var trees = [
	            [{tag: "Metadata/SourceName",
	            restrict: "Metadata/Extra/Project = '" + projectName + "'"},
	            {"prefixTag": "Path"}],
				];
			}
            $("#tree_div").empty();
            makeTagTree("#tree_div", trees[treeidx], selectCb, deselectCb, clearPlot,
                        page_args.path ? page_args.path.split(",") : []);
              
        }
        updateTree(projectName);

		//this is for permalink
		//toolkit metadata is not shown when permalink is selected--see comment below
        if ("streamids" in page_args) {
          clear_streams = true;
          var ids = page_args['streamids'].split(',');
          if ("axes" in page_args) {
            var axes = page_args['axes'].split(',');
          } else { 
            // if axes isn't specified, we want to just make it undefined
            var axes = [];
          }
          $.each(ids, function(i, streamid) {
            console.log(streamid + " " + axes[i]);
            //for permalink--metadata tags are just looked up here--would need to mess with this code to make the label and toolkit metadata show up for permalink
            $.get(backend + "/api/tags/uuid/" + escape(streamid) + "?" + private_flags, 
                  function (data) {
                    addStreams(data, defaultLabels, 1, axes[i]);
                  });
          });
        }
        function showHoo(){
				if (document.getElementById('hweekends').checked){
					$("#hoo").show();	
				}
				else {
					$("#hoo").hide();
				}
		}
      </script>

          </div><!--/span-->
      </div><!--/row-->
      <hr>
	{% include 'footer.html' %}

    </div><!--/.fluid-container-->
  </body>
</html>
